import { useMockData } from '@/config/env';
import { Response } from '@/types/third-party/api';
import { message } from 'antd';
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import store from 'store2';

export interface CustomAxiosInstance extends AxiosInstance {
  <T = any, R = T, D = any>(config: AxiosRequestConfig<D>): Promise<R>;
}

const baseURL = useMockData
  ? '/api'
  : 'https://qianwu-bom-t7ppdk.qunhefc.com/prod-api';

export const request = axios.create({
  baseURL: baseURL,
}) as CustomAxiosInstance;

request.interceptors.request.use((config) => {
  config.headers['Open-Authorization'] =
    'Bearer ' + store.get('apiConfig')?.apiKey;
  return config;
});
request.interceptors.response.use(
  (response: AxiosResponse<Response>) => {
    if (response.data.code !== 0) {
      message.error(response.data.message);
      return Promise.reject(response.data);
    }
    return response.data.data;
  },
  (error) => {
    console.error(error);
    message.error(error.message);
    return Promise.reject(error);
  },
);
